package com.feiwo.nonego.rpc.proxy.bytebuddy;

import com.feiwo.nonego.rpc.proxy.api.BaseProxyFactory;
import com.feiwo.nonego.rpc.proxy.api.ProxyFactory;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;

/**
 *
 *
 * @author feiwo 2025-08-15
 */
@SPIClass
public class BytebuddyProxyFactory<T> extends BaseProxyFactory<T> implements ProxyFactory {

    private static final Logger logger = LoggerFactory.getLogger(BytebuddyProxyFactory.class);

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getProxy(Class<T> clazz) {
        try {
            return (T) new ByteBuddy()
                    .subclass(Object.class)
                    .implement(clazz)
                    .intercept(InvocationHandlerAdapter.of(objectProxy))
                    .make()
                    .load(BytebuddyProxyFactory.class.getClassLoader())
                    .getLoaded()
                    .getDeclaredConstructor()
                    .newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            logger.error("bytebuddy proxy throws ex ---> ", e);
        }
        return null;
    }
}
